/**
 * Created by moko1988
 * 2016年01月16日16:10:34
 */
define([
    'backbone',
    'models/gameCategory/list',
    'text!templets/gameCategory/list.htm',
    'text!templets/gameCategory/list-modal-add.htm',
    'utils/dataTableUtil',
    'uploadify',
    'utils/urlUtil',
    'jquerypage',
    'select2'
], function(
    BackBone,
    Model,
    Tpl,
    ModalAdd,
    DataTable
) {
    var view = Backbone.View.extend({
        el: '#CONTENT',
        events: {
            'click [role=add]': 'addFun',
            'click [role=edit]': 'editFun',
            'click [role=save]': 'saveFun',
            'click [role=saveChange]': 'saveChange',
            'click [role=del]': 'delFun',
            'click [role=rank]': 'rank',
            'click #checkAll': 'checkAll', 
            'click input[name=idarr]': 'checkItem',
            'change #category': 'changeListCategory_ad',
            'click [role=search]': 'searchCharge'//查询
        },
        /*初始化*/
        initialize: function() {
            $(this.el).html(Tpl);
            $(this.el).off();
            this.page = '1';
            this.listRows = '10';
            this.idArr = [];
            $('#pageSize').select2();
            this.render();
        },
        
        /*渲染结果列表*/
        render: function() {
            $('#chart_table_div').html(loading);
            var _this = this;
            Model.fetchList({
                data: {
                    page: this.page,
                    page_size: this.listRows,
                },
                success: function(map) {
                    var data = map.list,
                        page = map.page,
                        count = data.length;
                         _this.pageTotal = page.total_page;

                    _.each(data,function(o, i){

                        o.checkbox = '<input type="checkbox" value="'+ o.id +'" name="idarr">';

                        var rank_up = '<button class="btn" role="rank" data-type="1" data-id="' + o.id+ '"><i class="glyphicon glyphicon-arrow-up"></i></button>',
                            rank_down = '<button class="btn" role="rank" data-type="0" data-id="' + o.id+ '"><i class="glyphicon glyphicon-arrow-down"></i></button>';

                        if (i == 0) {

                            rank_up = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-up"></i></button>';
                        }
                        if (i == (count - 1)) {

                            rank_down = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-down"></i></button>';
                        }

                        o.rank = rank_up + rank_down;

                        var btn_del = '<button class="btn" role="del" data-id="' + o.id+ '" >删除</button>';

                        o.btns = btn_del;
                    })

                     var tableHead = ['<input type="checkbox" id="checkAll">', '序号', '分类名称', '排序' ,'操作'],
                        tableBody = _.zip(
                            _.pluck(data,'checkbox'),
                            _.pluck(data,'id'),
                            _.pluck(data,'name'),
                            _.pluck(data,'rank'),
                            _.pluck(data,'btns')
                        );
                    DataTable.drawTable({
                        '$el': $('#chart_table_div'),
                        'thead': tableHead,
                        'tbody': tableBody
                    });

                     $("#pager").pager({
                        pagenumber: _this.page,
                        pagecount: _this.pageTotal,
                        buttonClickCallback: function(page){
                            _this.pageClick(page);
                        }
                    });
                }
            })
        },
         /*分页*/
        pageClick: function(page) {
            var _this = this;
            this.page = page;
            $("#pager").pager({
                pagenumber: this.page,
                pagecount: this.pageTotal,
                buttonClickCallback: function(page){
                    _this.pageClick(page);
                }
            });
            this.render();
        },
        /*全选、取消*/
        checkAll: function(e) {
            var $target = $(e.currentTarget),
                isCheck = $target.prop('checked'),
                _this = this;
            if (isCheck) {
                $('input[name=idarr]').prop('checked', true);
                $('input[name=idarr]').each(function() {
                    _this.idArr.push($(this).val());
                })
            } else {
                $('input[name=idarr]').prop('checked', false);
                this.idArr = [];
            }
        },
        /*选择、取消单条记录*/
        checkItem: function() {
            this.idArr = [];
            var isCheckAll = true,
                _this = this;
            $('input[name=idarr]').each(function() {
                if ($(this).prop('checked')) {
                    _this.idArr.push($(this).val());
                } else {
                    isCheckAll = false;
                }
            })
            if (isCheckAll) {
                $('#checkAll').prop('checked', true);
            } else {
                $('#checkAll').prop('checked', false);
            }
        },

        //添加
        addFun: function() {
            $(this.el).append(ModalAdd);
            var $myModal = $('#myModal');
            $myModal.find('h4').html('添加分类');
            $myModal.off();
            $myModal.modal();
            $myModal.on('hidden.bs.modal', function(e) {
                $myModal.remove();
            });
        },
        //添加提交
         saveFun: function() {
            var _this = this,
                $myModal = $('#myModal'),
                $form = $myModal.find('form[role=form]'),
                subBtn = $myModal.find('button[role=save]'),
        
                isOK = this.checkForm();

                 if(isOK){
                    subBtn.prop('disabled', true);
                    Model.insert({
                        type: 'post',
                        data: $form.serialize(),
                        success: function() {
                            subBtn.prop('disabled', false);
                            jAlert('提交成功', function() {
                                $myModal.modal('hide');
                                _this.render();
                            })
                        },
                        error:function(msg){
                            jAlert(msg,function(){
                                subBtn.prop('disabled', false);
                            })
                        }
                    })
              }
        },
     
        

        
        /*验证*/
        checkForm: function() {
            var $form = $('[role=form]'),
                $name = $form.find('input[name=name]'),
                $width = $form.find('input[name=width]'),
                $height = $form.find('input[name=height]'),
                $key = $form.find('input[name=key]'),
                errShow = function(e, msg) {
                    var $err = e.siblings('em');
                    $err.html(msg).css("opacity", '1');
                    $err.stop(0, 0).animate({
                        "opacity": 0
                    }, 3500);
                    rest = false;
                },
                rest = true;
            if ($name.val() == '') {
                errShow($name, '请填写合作客户！');
            }

            if ($key.val() == '') {
                errShow($key, '请填写链接！');
            }
            return rest;
        },
        /*删除*/
        delFun: function(e) {
            var $target = $(e.currentTarget),
                id = $target.attr('data-id'),
                _this = this,
                msg = '<p>确定要删除该分类？</p>';
            jConfirm(msg, function(s) {
                if (s) {
                    Model.delete({
                        type: 'post',
                        data: {
                            id: id
                        },
                        success: function(map) {
                            jAlert('删除成功', function() {
                                _this.render();
                            })
                        }
                    })
                }
            })
        },
        rank: function(e){
            var $target = $(e.currentTarget),
                type = $target.attr('data-type'),
                id = $target.attr('data-id'),
                _this = this;
            Model.rank({
                type:'post',
                data: {
                    id: id,
                    type: type
                },
                success: function() {
                    jAlert('操作成功！', function() {
                        _this.render();
                    });
                }
            })
        },
        
    })
    return view;
})